<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <nav id="nav">
        <ul>
            <li>
                <a href="#/page1">页面一</a>
            </li>
            <li>
                <a href="#/page2">页面二</a>
            </li>
            <li>
                <a href="#/page3">页面三</a>
            </li>
        </ul>
    </nav>
    <div id="router-view">

    </div>
    <script>
        class HashRouter{
            constructor(){
                this.routes = {}; //对象 page=> Component
                window.addEventListener('hashchange',this.load.bind(this),false);

            }

            register(hash,callback=function(){}){
                this.routes[hash]=callback;
            }

            registerIndex(callback=function(){}){
                this.routes['index']=callback;
            }

            load(){ 
                // console.log(location.hash); //BOM
                let hash = location.hash.slice(1) //去掉# 才是路由
                console.log(hash,'////');
                let handler;
                if(!hash){
                    handler =this.routes['index']
                    //去首页
                }else{
                    handler = this.routes[hash]
                    //相应页面
                }
                handler && handler.call(this) // 执行相应页面的函数  重点 如果用户输入错误的URL则不执行
            }    
        }
    </script>
</body>
</html>